//格式化相关
jQuery.extend({
    //form 提交
    yqFormAjax: function (ajaxUrl, formData, callback) {
        $.ajax({
            type: 'POST',
            url: ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if ($.yqDataErrCheck(res)) {
                    callback(res);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                callback({ "error": 99, "info": errorThrown });
            }
        });
    },

    //数据库端错误前置跳转处理
    //true:正常执行  false:跳转执行
    yqDataErrCheck: function (res) {
        if (res.error != 0) {
            console.error(res)
        }

        if (res.error == 404) {
            if (window.top == window.self) {
                $.messager.alert({
                    title: '重新登录',
                    msg: '登录状态已退出!',
                    fn: function () {
                        location.href = "/login/login.html?backurl=" + encodeURIComponent(window.location.href);
                    }
                });
            }
            else {
                window.top.$.messager.alert({
                    title: '重新登录',
                    msg: '登录状态已退出!',
                    fn: function () {
                        window.top.window.location.href = "/login/login.html?backurl=" + encodeURIComponent(window.top.window.location.href);
                    }
                });

            }
            return false;
        }
        return true;
    },
    //返回url连接？后面的参数值
    urlRequest: function (paras) {
        var url = location.href;
        return $.urlParam(url, paras);
    },
    urlParam: function (url, paras) {
        if (url === undefined || url === null || url === "") {
            return "";
        }
        if (url.endsWith('#')) {
            url = url.slice(0, -1);
        }
        var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
        var _paras = paras.toLowerCase();
        for (i = 0; j = paraString[i]; i++) {
            if (j.substring(0, j.indexOf("=")).toLowerCase() == _paras) {
                return decodeURIComponent(j.substring(j.indexOf("=") + 1, j.length));
            }
        }
        return "";
    },
    // 删除url指定参数  url:url地址  paramsToRemove:需要删除的参数,如["id","name"]
    urlRemoveParams: function (url, paramsToRemove) {
        const urlObj = new URL(url);
        const searchParams = urlObj.searchParams;
        for (let param of paramsToRemove) {
            searchParams.delete(param);
        }
        return `${urlObj.origin}${urlObj.pathname}${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
    },
    //页面流水id
    getUniqueID: function () {
        var cno = $("body").data("UniqueNo");
        if (cno === undefined) {
            cno = 0;
        }
        cno++;
        $("body").data("UniqueNo", cno);

        return "id" + cno;
    },
    //页面流水序号
    getKeyAdd: function () {
        var cno = $("body").data("UniqueNo");
        if (cno === undefined) {
            cno = 0;
        }
        cno++;
        $("body").data("UniqueNo", cno);

        return cno;
    },
    getShortID: function () {
        return shortid.gen();;
    },
    //json格式化显示输出
    jsonFormat: function (str) {
        try {
            // 设置缩进为2个空格
            if (typeof str == "string") {
                str = JSON.stringify(JSON.parse(str), null, 2);
            } else {
                str = JSON.stringify(str, null, 2);
            }

            str = str
                .replace(/&/g, '&')
                .replace(/</g, '<')
                .replace(/>/g, '>');
            return str.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                var cls = 'number';
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = 'key';
                    } else {
                        cls = 'string';
                    }
                } else if (/true|false/.test(match)) {
                    cls = 'boolean';
                } else if (/null/.test(match)) {
                    cls = 'null';
                }
                return match;
            });
        } catch (e) {
            alert("异常信息:" + e);
        }
    },
    //json去除空数据 去除所有无效的 null、""、{} 和 []。
    jsonRemoveEmpty: function (value) {
        return cleanJson(value);

        function cleanJson(obj) {
            if (Array.isArray(obj)) {
                // 处理数组：递归清理每个元素，并过滤掉空数组或无效元素
                const cleanedArray = obj.map(cleanJson).filter(item => {
                    return item !== null && item !== undefined && !(Array.isArray(item) && item.length === 0);
                });
                return cleanedArray.length > 0 ? cleanedArray : undefined;
            } else if (typeof obj === 'object' && obj !== null) {
                // 处理对象：递归清理每个属性，并过滤掉空对象或无效属性
                const newObj = {};
                for (const key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        const cleanedValue = cleanJson(obj[key]);
                        if (cleanedValue !== null && cleanedValue !== undefined && !(typeof cleanedValue === 'object' && Object.keys(cleanedValue).length === 0)) {
                            newObj[key] = cleanedValue;
                        }
                    }
                }
                return Object.keys(newObj).length > 0 ? newObj : undefined;
            } else {
                // 处理基本类型：过滤掉 null 和空字符串
                return obj !== null && obj !== "" ? obj : undefined;
            }
        }
    },

    /**
    * 动态加载JS CSS
    * @param {string,Object,Array} file 脚本地址 url,{url:"2.css",type："css"},[{url:"2.css",type："css"}]
    * @param {function} callback  回调函数
    */
    yqLoadJsCss: function (file, callback) {
        if (typeof file == "string") {
            loadFile(file,
                file.substring(file.lastIndexOf(".") + 1).toLowerCase(),
                function () {
                    if (typeof (callback) == 'function') {
                        callback();
                    }
                });
        } else if (typeof file == "object") {
            if (Array.isArray(file)) {
                if (file.length > 0) {
                    loadFiles(file, 0);
                }
            } else {
                loadFiles([file], 0);
            }
        } else {
            if (typeof (callback) == 'function') {
                callback();
            }
        }


        function loadFiles(file, i) {
            if (i >= file.length) {
                if (typeof (callback) == 'function') {
                    callback();
                }
                return;
            }

            if (file[i].type === undefined || file[i].type === null) {
                loadFile(file[i].url,
                    file[i].substring(file[i].lastIndexOf(".") + 1).toLowerCase(),
                    function () {
                        loadFiles(file, i + 1);
                    });
            } else {
                loadFile(file[i].url,
                    file[i].type,
                    function () {
                        loadFiles(file, i + 1);
                    });
            }
        }

        function loadFile(url, fileType, callback) {
            let fileHref;
            if (fileType == "js") {
                var scripts = $('script');
                for (let i = 0; i < scripts.length; i++) {
                    if ($(scripts[i]).attr("src") == url) {
                        callback();
                        return;
                    }
                }

                fileHref = document.createElement('script');
                fileHref.setAttribute("type", "text/javascript");
                fileHref.setAttribute("src", url);
            } else if (fileType == "css") {
                var links = $('link');
                for (let i = 0; i < links.length; i++) {
                    if ($(links[i]).attr("href") == url) {
                        if (typeof (callback) == 'function') {
                            callback();
                        }
                        return;
                    }
                }

                fileHref = document.createElement('link');
                fileHref.setAttribute("rel", "stylesheet");
                fileHref.setAttribute("type", "text/css");
                fileHref.setAttribute("href", url);
            }

            if (fileHref !== undefined) {
                document.getElementsByTagName("head")[0].appendChild(fileHref);
                if (typeof (callback) == 'function') {
                    fileHref.onload = function () {
                        if (!this.readyState || this.readyState == 'loaded'
                            || this.readyState == 'complete') {
                            if (typeof (callback) == 'function') {
                                callback();
                            }
                        } else {
                            console.error("yqLoadJsCss,url=" + url + ",未加载。");
                            if (typeof (callback) == 'function') {
                                callback();
                            }
                        }
                    }

                    fileHref.onerror = function () {
                        console.error("yqLoadJsCss,url=" + url + ",未加载。");
                        if (typeof (callback) == 'function') {
                            callback();
                        }
                    };
                }
            } else {
                if (typeof (callback) == 'function') {
                    callback();
                }
            }
        }
    },
    //css 文本，css名称
    yqAddCSS: function (cssText, cssName) {
        if (cssName) {
            const existingStyles = document.querySelectorAll('style[name]');
            for (const style of existingStyles) {
                if (style.getAttribute('name')?.includes(cssName)) {
                    return;
                }
            }
        }

        const style = document.createElement('style');
        style.name = cssName;
        style.textContent = cssText;

        const head = document.head || document.getElementsByTagName('head')[0];
        head.appendChild(style);
    },

    //转换窗体设置的尺寸参数  50%,200px 转 int类型
    whFormat: function (wh) {
        if (!wh) return 100;

        if (typeof wh !== "string") return wh;

        if (wh.slice(-1) === "%") {
            const scale = parseInt(wh);
            return Math.floor(scale * $(window).width() / 100);
        } else if (wh.slice(-2) === "px") {
            return parseInt(wh.slice(0, -2));
        } else if (wh.slice(-2) === "em") {
            return parseInt(wh.slice(0, -2)) * 16;
        } else if (wh.slice(-3) === "rem") {
            return parseInt(wh.slice(0, -3)) * 16;
        }

        return parseInt(wh);
    },

    //头部窗体
    topWindow: function () {
        return window.top === window.self ? window : window.top;
    },
    //格式化url
    fmtUrl: function (eurl) {
        if (!eurl) return null;

        if (eurl.length > 5) {
            const isAbsolute = eurl.startsWith('/') || eurl.toLowerCase().startsWith('http');
            if (!isAbsolute) {
                const pathname = window.location.pathname;
                const basePath = pathname.substring(0, pathname.lastIndexOf('/') + 1);
                return basePath + eurl;
            }
        }

        return eurl;
    },
    
    //下载文件 
    downloadFile: function (url, filename) {
        // 根据文件扩展名获取 MIME 类型
        var getMimeType = function(filename) {
            var ext = filename.split('.').pop().toLowerCase();
            var mimeTypes = {
                // JSON 文件
                'json': 'application/json',
                
                // 文本文件
                'txt': 'text/plain',
                'csv': 'text/csv',
                'xml': 'text/xml',
                'html': 'text/html',
                'htm': 'text/html',
                'css': 'text/css',
                'js': 'text/javascript',
                'md': 'text/markdown',
                
                // 图片文件
                'jpg': 'image/jpeg',
                'jpeg': 'image/jpeg',
                'png': 'image/png',
                'gif': 'image/gif',
                'bmp': 'image/bmp',
                'webp': 'image/webp',
                'svg': 'image/svg+xml',
                'ico': 'image/x-icon',
                
                // 音频文件
                'mp3': 'audio/mpeg',
                'wav': 'audio/wav',
                'ogg': 'audio/ogg',
                'm4a': 'audio/mp4',
                
                // 视频文件
                'mp4': 'video/mp4',
                'avi': 'video/x-msvideo',
                'mov': 'video/quicktime',
                'wmv': 'video/x-ms-wmv',
                'flv': 'video/x-flv',
                'webm': 'video/webm',
                
                // 压缩文件
                'zip': 'application/zip',
                'rar': 'application/x-rar-compressed',
                '7z': 'application/x-7z-compressed',
                'tar': 'application/x-tar',
                'gz': 'application/gzip',
                
                // PDF 文档
                'pdf': 'application/pdf',
                
                // Office 文档
                'doc': 'application/msword',
                'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'xls': 'application/vnd.ms-excel',
                'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'ppt': 'application/vnd.ms-powerpoint',
                'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                
                // 其他常见文件
                'exe': 'application/octet-stream',
                'dll': 'application/octet-stream',
                'bin': 'application/octet-stream'
            };
            
            return mimeTypes[ext] || 'application/octet-stream';
        };

        // 创建 XMLHttpRequest 对象获取文件内容
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        
        // 设置请求头，支持跨域下载
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

        xhr.onload = function () {
            if (xhr.status === 200) {
                // 获取文件类型
                var mimeType = getMimeType(filename);
                
                // 尝试从响应头获取实际的 MIME 类型
                var contentType = xhr.getResponseHeader('Content-Type');
                if (contentType && contentType.indexOf('application/octet-stream') === -1) {
                    mimeType = contentType.split(';')[0]; // 移除 charset 等参数
                }
                
                // 创建 Blob 对象
                var blob = new Blob([xhr.response], { type: mimeType });

                // 创建下载链接
                var downloadUrl = window.URL.createObjectURL(blob);
                var link = document.createElement('a');
                link.href = downloadUrl;
                link.download = filename;
                
                // 设置链接样式，确保不会在页面上显示
                link.style.display = 'none';

                // 触发下载
                document.body.appendChild(link);
                link.click();

                // 清理
                document.body.removeChild(link);
                window.URL.revokeObjectURL(downloadUrl);
            } else {
                console.error('下载失败，状态码:', xhr.status);
                
                // 显示错误消息给用户
                if (window.$ && $.messager) {
                    var errorMsg = xhr.status === 404 ? '文件不存在' : 
                                  xhr.status === 403 ? '没有下载权限' : 
                                  xhr.status === 500 ? '服务器错误' : 
                                  '下载失败，请稍后重试';
                    
                    $.messager.show({
                        title: '错误',
                        msg: errorMsg + ' (状态码: ' + xhr.status + ')',
                        timeout: 3000
                    });
                }
            }
        };
        
        xhr.onerror = function () {
            console.error('下载请求失败');
        };
        
        xhr.ontimeout = function () {
            console.error('下载请求超时');
        };
        
        // 设置超时时间（30秒）
        xhr.timeout = 30000;
        
        // 发送请求
        xhr.send();
    },

});

//js-shortid
(function (root, factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof (module) !== 'undefined' && module.exports) {
        module.exports = factory();
    } else {
        var _previousRoot = root.shortid;
        var self = factory();
        self.noConflict = function () {
            root.shortid = _previousRoot;
            return self;
        };
        root.shortid = self;
    }
}(this, function () {
    var __initime = 1460332800000,//2016-04-11
        __symbols = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
            'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
        __base = 62,
        __paddingLeft = function (padding, val) {
            return (padding + val).slice(-padding.length);
        },
        ShortId = function (opt) {
            this._opt = opt || {};
        };
    ShortId.prototype = {
        _toBase: function (decimal, base) {
            var opt = this._opt,
                symbols = opt.symbols || __symbols,
                conversion = "";
            if (base > symbols.length || base <= 1) {
                return false;
            }
            while (decimal >= 1) {
                conversion = symbols[(decimal - (base * Math.floor(decimal / base)))] +
                    conversion;
                decimal = Math.floor(decimal / base);
            }
            return (base < 11) ? parseInt(conversion) : conversion;
        },
        _salts: function () {
            var self = this, opt = self._opt, salts = opt.salts || 2,
                ret = '';
            for (var i = 0; i < salts; i++) {
                var salt = Math.floor(Math.random() * 3844);
                ret += __paddingLeft('00', self._toBase(salt, __base));
            }
            return ret;
        },
        gen: function () {
            var self = this, opt = self._opt, interval = opt.interval || 1,
                initime = opt.initTime || __initime,
                //default millisecond since init time
                elapsed = interval > 0 ? Math.floor((new Date().getTime() - initime) / interval) : 0,
                salts = self._salts();
            return elapsed === 0 ? salts : (self._toBase(elapsed, __base) + salts);
        }
    };
    return {
        inst: function (opt) {
            return new ShortId(opt);
        },
        gen: function (opt) {
            return new ShortId(opt).gen();
        },
        uuid: function () {
            return new ShortId({ salts: 4 }).gen();
        }
    };
}));
